<-- back

Add Two Numbers

Link

A bit tricky simply because they had test cases which required me to use long instead of int. I basically converted all the Nodes to ints, summed them up, and then converted it back into a linked list again. Nothing too fancy.

Full Solution in Java:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { long one = nodeToInt(l1); long two = nodeToInt(l2); long sum = one+two; if(sum==0){ return new ListNode(0); } ListNode head = new ListNode(0); ListNode ret = head; while(sum>0){ head.next = new ListNode((int)(sum%10)); head = head.next; sum/=10; } return ret.next; } long nodeToInt(ListNode l){ int i = 0; long ret = 0; while(l!=null){ ret+=Math.pow(10,i)*l.val; i++; l = l.next; } return ret; } }